#!/usr/bin/python
#-*- coding:utf-8 -*
#django添加数据库用户密码
import sys
import os
from optparse import OptionParser

os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "mysite.settings" )
from jobs.models import Admin



###编码转移,可以输出中文####
reload(sys)
sys.setdefaultencoding('utf-8')


###%prog表示脚本本身
MSG_USAGE = "%prog [ -n <hostname>][-i <server_ip>][-p <server_port>][-w <business>][-o <owner>][-h <help>]"
MSG_VERSION = "%prog 20140703"

###usage打印用法,version输出版本信息
optParser = OptionParser(usage=MSG_USAGE,version=MSG_VERSION)

###对optParser增加选项
optParser.add_option("-n","--hostname",action = "store",type = "string",dest = "HostName",help="添加服务器名称(必填)")
optParser.add_option("-i","--server_ip",action = "store",type = "string",dest = "Server_Ip",help="添加服务器IP(必填)")
optParser.add_option("-p","--server_port",action = "store",type = "string",dest = "Server_Port",help="添加服务器端口(必填)")
optParser.add_option("-w","--work",action = "store",type = "string",dest = "Work",help="添加JOB业务(必填)")
optParser.add_option("-o","--owner",action = "store",type = "string",dest = "Owner",help="添加负责人(必填)")

#fakeArgs = ['-u','leon','-p','123456','-t','a']
options,args = optParser.parse_args()

HOSTNAME= options.HostName
SERVER_IP = options.Server_Ip
SERVER_PORT = options.Server_Port
WORK = options.Work
OWNER = options.Owner


#判断参数-u,-p是否为空,返回帮助
args_list = [HOSTNAME,SERVER_IP,SERVER_PORT,WORK,OWNER]
for i in args_list:
    if i is None:
        print '请使用(-h,--help)来获得帮助'
        sys.exit(0)


#User是在accounts中models.py的类,定义了数据库的一些信息,插入用户
#判断用户是否存在
def init():
    CHECK_NAME=Admin.objects.filter(server_name=HOSTNAME,server_ip=SERVER_IP,server_port=SERVER_PORT,job_work=WORK,job_owner=OWNER)
    if len(CHECK_NAME) > 0:
        print "数据已存在"
    else:
        u = Admin(server_name=HOSTNAME,server_ip=SERVER_IP,server_port=SERVER_PORT,job_work=WORK,job_owner=OWNER)
        u.save()

if '__main__' == __name__:
    init()
